//服务器地址
var imgUrl = 'http://192.168.1.105/';
var serverUrl = 'http://192.168.3.4/thinkphp/public/index.php/index/';

//var imgUrl = 'http://guo.21dianshang.com';
//var serverUrl = 'http://guo.21dianshang.com/tools/apis/';

//重新获取缓存
function getStorageAll() {
	user_id = $api.getStorage('user_id');
	group_id = $api.getStorage('group_id');
	user_name = $api.getStorage('user_name');
	nick_name = $api.getStorage('nick_name');
	birthday = $api.getStorage('birthday');
	sex = $api.getStorage('sex');
	avatar = $api.getStorage('avatar');
	lat = $api.getStorage('lat');
	lon = $api.getStorage('lon');
}

//重新登录监听
function sendReGetMyInfo() {
	api.sendEvent({
		name : 'reGetMyInfo',
		extra : {
			key : 'true'
		}
	});
}

//两次退出
var first = null;
function back() {
	api.addEventListener({
		name : 'keyback'
	}, function(ret, err) {
		if (!first) {
			first = new Date().getTime();
			api.toast({
				msg : '再按一次回到桌面',
				duration : 1500,
				location : 'bottom'
			});
			setTimeout(function() {
				first = null;
			}, 1500);
		} else {
			if (new Date().getTime() - first < 1500) {
				//回到系统桌面
				api.toLauncher();
			}
		}
	});
}

//关闭窗体
function closeWin() {
	api.closeWin();
}

//打开窗体-无提示
function openToTwo(winname) {
	api.openWin({
		name : winname,
		url : '' + winname + '.html',
		delay : 300,
        vScrollBarEnabled:false
	});
}

//打开窗体-有提示
function openTo(winname) {
	api.toast({
		msg : '请先登录',
		duration : 2000,
		location : 'bottom'
	});
	api.openWin({
		name : winname,
		url : '' + winname + '.html',
		delay : 300
	});
}

//打开窗体-判断登录
function openWin(name) {
	getStorageAll();
	if (!user_id) {
		api.openWin({
			name : 'login_win',
			url : 'login_win.html',
			delay : 300
		})
	} else {
		api.openWin({
			name : '' + name + '',
			url : '' + name + '.html',
			delay : 300
		})
	}
}

//切换帐号
function changeAccount() {
	$api.clearStorage();
	api.sendEvent({
		name : 'reGetMyInfo',
		extra : {
			key : 'true'
		}
	});
	api.openWin({
		name : 'login_win',
		url : 'login_win.html',
		delay : 300
	})
}

//清除缓存
function clearCache() {
	api.clearCache();
	api.toast({
		msg : '清除成功',
		duration : 2000,
		location : 'bottom'
	});
}

function ajaxRequest(url, method, datas, callBack) {
	var now = Date.now();
	api.ajax({
		url : serverUrl + url,
		method : method,
		cache : false,
		timeout : 60,
		dataType : 'json',
		data : {
			values : datas
		}
	}, function(ret, err) {
		callBack(ret, err);
	});
}

function getLocation(callBack) {
	var baiduLocation = api.require('baiduLocation');
	baiduLocation.startLocation({
		accuracy : '500m',
		filter : 1,
		autoStop : true
	}, function(ret, err) {
		var sta = ret.status;
		var lat = ret.latitude;
		var lon = ret.longitude;
		var location = '' + lat + ',' + lon + '';
		var ak = '4880fdc9318f40e4afac92629b9bbb66';
		api.ajax({
			url : 'http://api.map.baidu.com/geocoder/v2/?ak=' + ak + '&location=' + location + '&output=json&pois=0',
			method : 'get',
			timeout : 60,
			dataType : 'json',
			data : {}
		}, function(ret, err) {
			//if (ret.status == 0) {
			//	var address = ret.result.formatted_address;
			//}
			callBack(ret, err);
		});
	})
}

function showLoading(time) {
	var body = $api.dom("body");
	var loading = $api.byId("loading");
	if (!loading) {
		$api.append(body, '<div class="aui-loading" id="loading"></div>');
		if (time && time > 0) {
			//如果有时间传进来就定时隐藏
			$api.remove(loading);
		}
	}
}

function hideLoading() {
	var loading = $api.byId("loading");
	setTimeout(function() {
		$api.remove(loading);
	}, 500);

}

//BMAP获取地理位置
function updateLocation() {
	//更新位置信息
	var map = api.require('bMap');
	map.getLocation({
		accuracy : '100m',
		autoStop : true,
		filter : 1
	}, function(ret, err) {
		if (ret.status) {
			var data = {};
			var lat = ret.lat;
			var lon = ret.lon;
			//更新缓存
			$api.setStorage('lat', '' + lat + '');
			$api.setStorage('lon', '' + lon + '');
			data['lat'] = lat;
			data['lon'] = lon;
			data['user_id'] = $api.getStorage('user_id');
			var url = 'user_ajax.ashx?action=updateLocation';
			ajaxRequest(url, 'post', data, function(ret, err) {
				//alert(JSON.stringify(ret.msg));
			});
		} else {
			alert(err.code);
		}
	})
}

function formatDate(time) {
	//var newTime = time.substring(0,10);
	var date = new Date(time * 1000);
	var hour = date.getHours();
	var minute = date.getMinutes();
	var second = date.getSeconds();
	return hour + ':' + minute;
}


function openPicker(dateType) {
	var dateType = $api.byId('' + dateType + '');
	if (api.systemType == 'android') {
		api.openPicker({
			type : 'date',
			title : '选择时间'
		}, function(ret, err) {
			var year = ret.year;
			var month = ret.month;
			var day = ret.day;
			var value1 = year + '-' + month + '-' + day;
			$api.val(dateType, '' + value1 + '');
		});
	} else if (api.systemType == 'ios') {
		api.openPicker({
			type : 'date_time',
			title : '选择时间'
		}, function(ret, err) {
			var year = ret.year;
			var month = ret.month;
			var day = ret.day;
			var hour = ret.hour;
			var minute = ret.minute;
			var value1 = year + '-' + month + '-' + day;
			$api.val(dateType, '' + value1 + '');
		});
	}
}

//微信支付接口
function wxpay(subject, body, amount, tradeNO) {
	var wxPay = api.require('wxPay');
	wxPay.config({
		apiKey : 'wxdbe76a72b62982ed',
		mchId : '1354204002',
		partnerKey : '38jfjksfu8kk3jdjfdjf3jkdjf34jjfd',
		notifyUrl : 'http://riyu.21dianshang.com/tools/weixinpay/return_url.aspx'
	}, function(ret, err) {
		if (ret.status) {
			//alert("配置成功！" + err.code);
			wxPay.pay({
				description : subject, //简要描述
				totalFee : amount,     //订单金额
				tradeNo : tradeNO,     //订单编号
				detail : body,         //明细列表
				feeType : 'CNY'
			}, function(ret, err) {
				if (ret.status) {
					api.toast({
						msg : '支付成功',
						location : 'middle'
					});
					sendReGetMyInfo();
					notify_url(tradeNO);
				} else {
					//alert("error" + err.code);
					//alert("msg:" + err.msg);
					api.toast({
						msg : '支付失败',
						location : 'middle'
					})
				}
			})
		} else {
			//alert("配置失败 error" + err.code);
		}
	})
}

//支付宝接口
function aliPay(subject, body, amount, tradeNO) {
	var obj = api.require('aliPay');
	obj.pay({
		partner : '2088121477780128',
		seller : '1546708912@qq.com',
		rsaPriKey : 'MIICXgIBAAKBgQCrwk177oI6lEx9CcJanPYIiq1BDksRoFvXD+46xcQw7E+KcM5Y70CqXECaglwaKmMl6EeVWUj2MYEOxbvYwT+GTBFnvocUqDLqhV0JCrYANVtZas5TQIqkUr9yzdYnIoHmSBnxfaGKkqKR28SKlMjdRKfjmRvJjVn3DcNFMirWVQIDAQABAoGBAKjKJYMo/Gm82v313T1XCqGSRnisJzGHOTm7ug2f1BGP6QrPmLjlRdMlHYe5m/FKvmy+O7qVJ5JpS77MqrF0F4uyQ8mKTbChnkzls0gWW/QlHHRXUVW+sT9CM9XTUzbLOos+mqwiE6OJUTze/ghmGhZHh63xPJLdMbDAc/GIySXxAkEA2Xuu0KGqEjI4R32JFMh8F1962PTl9TD2ibv24XvLlKwzvbO6uOv3wv3nVueuoDQ8DxotnPQ89duc1dqhfD/C8wJBAMotkI1C4O3+25i9HiO8BsatNUmH+AjQeSC4NxC2FxCKUsXG21/Ttnhd97X3FIKFyzm6NUYX+6jakAOk1eciA5cCQCrRfhaXbauNdaUloyKTYlMbuk0S0l+W10NA3ZeBTxCjYsB7rUyRMMOUR8LFdI0YG6cBiW94arQhG9zC4b5bs18CQQC86BQfmXS3i6E9tr8Zno8qRh77JJuCCOCUzOtOpwUoBEbQ2zyQ7i2ZjBtvH30/c6nut2kdpD0ViZp0fSkMPMDjAkEAk7hh0Y4e+HhSV1LmSkJcXQ+oLlYr1Y8BGMePchwqLW4yVVWlx+pSoj61wnFb6SPaZaTKVqwvvjtEn3SGhXe8vg==',
		rsaPubKey : 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB',
		subject : subject, //订单名
		body : body, //订单描述
		amount : amount, //金额
		tradeNO : tradeNO, //订单编号
		notifyURL : 'http://fqfm.21dianshang.com/tools/alipayapp/notify_url.aspx'
	}, function(ret, err) {
		if (ret.code == 9000) {
			sendReGetMyInfo();
			notify_url(tradeNO);
			//api.closeToWin({
			//	name : 'root',
			//	animation : {
			//		type : 'flip',
			//		subType : 'from_bottom',
			//		duration : 500
			//	}
			//})
		}
	});
}

//9000：支付成功
//4000：系统异常
//4001：数据格式不正确
//4003：该用户绑定的支付宝账户被冻结或不允许支付
//4004：该用户已解除绑定
//4005：绑定失败或没有绑定
//4006：订单支付失败
//4010：重新绑定账户
//6000：支付服务正在进行升级操作
//6001：用户中途取消支付操作
//0001：缺少商户配置信息（商户id，支付公钥，支付密钥）
//0002：缺少参数（subject、body、amount、tradeNO）
//0003：签名错误（公钥私钥错误）

//支付回调
function notify_url(tradeNO) {
	var url = 'user_ajax.ashx?action=notify_url';
	var data = {};
	data['order_no'] = tradeNO;
	ajaxRequest(url, 'post', data, function(ret, err) {
		// alert(JSON.stringify(ret));
		//关闭到指定窗口，最上面显示的窗口到指定name窗口间的所有窗口都会被关闭
		api.closeToWin({
			name : 'root',
			animation : {
				type : 'flip',
				subType : 'from_bottom',
				duration : 500
			}
		});
	})
}